package com.leo.erp.service.impl;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leo.erp.dao.TenantMapper;
import com.leo.erp.dto.TenantExecution;
import com.leo.erp.entity.Tenant;
import com.leo.erp.enums.TenantStateEnum;
import com.leo.erp.service.TenantService;
import com.leo.erp.util.GlobalRuntimeException;

@Service
public class TenantServiceImpl implements TenantService{
	@Autowired
	private TenantMapper tenantMapper;

	@Override
	public TenantExecution getTenantByTenantId(int tenantId) {
		Tenant tenant = new Tenant();
		QueryWrapper<Tenant> queryWrapper = new QueryWrapper<>();
		List<Tenant> tenantList = tenantMapper.selectList(queryWrapper);
		TenantExecution te = new TenantExecution();
		if(tenantList.size() > 0) {
			tenant = tenantList.get(0);
			te.setState(TenantStateEnum.SUCCESS.getState());
			te.setTenant(tenant);
		}else {
			te.setState(TenantStateEnum.OFFLINE.getState());
		}
		return te;
	}

	@Override
	@Transactional
	public TenantExecution insertTenant(String beanJson, HttpServletRequest request) throws GlobalRuntimeException {
		Tenant tenant = JSONObject.parseObject(beanJson, Tenant.class);
		TenantExecution te = new TenantExecution();
		int result = 0;
		try {
			tenant.setUserNumLimit(1000000);//默认用户限制数量
			tenant.setBillsNumLimit(100000000);//默认单据限制数量
			tenant.setCreateTime(new Date());
			result = tenantMapper.insert(tenant);
			if(result > 0) {
				te.setState(TenantStateEnum.SUCCESS.getState());
			}else {
				te.setState(TenantStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		return te;
	}

}
